<template>
  <div class="import">
    <div class="app-container">
      <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" :href="href" />
      <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
        <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
      </el-table>
    </div>
  </div>
</template>

<script>
import { dateFormatExcel } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  computed: {
    type() {
      return this.$route.query.type
    },
    href() {
      if (this.type === 'employee') {
        return './excel/员工导入模板.xlsx'
      } else if (this.type === 'salarys') {
        return './excel/薪资导入模板.xlsx'
      } else {
        return ''
      }
    }
  },
  methods: {

    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      if (this.type === 'employee') {
        this.import(results)
      }
    },
    async import(results) {
      const relation = {
        '入职日期': 'timeOfEntry',
        '姓名': 'username',
        '工号': 'workNumber',
        '手机号': 'mobile',
        '转正日期': 'correctionTime',
        '聘用形式': 'formOfEmployment',
        '组织结构': 'departmentName'
      }
      const list = results.map(item => {
        const obj = {}
        Object.keys(item).forEach(k => {
          if (k === '入职日期' || k === '转正日期') {
            // return dateFormat(item[k])
            obj[relation[k]] = dateFormatExcel(item[k])
          } else {
            obj[relation[k]] = item[k]
          }
        })
        return obj
      })
      await importEmployee(list)
      this.$message.success('导入成功')
      this.$router.back()
      // console.log(list, '-----')
      // console.log(dateFormatExcel(43719), '--------------')
    }
  }
}
</script>

<style>

</style>
